package com.whut.service.impl;


import java.sql.*;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.mapping.Map;
import org.springframework.stereotype.Component;

import com.whut.dao.UserDao;
import com.whut.dao.impl.UserDaoImpl;
import com.whut.model.User;
import com.whut.service.UserManager;
import com.whut.util.UtilCommon;
import com.whut.vo.UserRegisterInfo;
@Component("um")
public class UserManagerImpl implements UserManager {
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}
    @Resource(name="userDao")
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public boolean exists (User u)throws Exception{
		return userDao.checkUserWithName(u.getUsername());		
	}	 
	
	@Override
	public boolean legalUser(User u) throws Exception {
		u.setPassword(UtilCommon.md5Encryption(u.getPassword()));
		System.out.println(u.getPassword());
		return userDao.checkUser(u.getUsername(),u.getPassword());
	}
	
	@Override
	public void add (User u)throws Exception{
		//往数据库添加u
		u.setPassword(UtilCommon.md5Encryption(u.getPassword()));
		userDao.save(u);		
   	}
	
	@Override
	public void add (UserRegisterInfo info)throws Exception{
		//往数据库添加u
		userDao.save(info);		
   	}
	
	@Override
	public List<User> getUsers() throws Exception {
		// TODO Auto-generated method stub
		return userDao.getUsers();
	}	
	
	//每次登录，往数据库修改 loginTimes的值
	@Override
	public void addLoginTimes(User u) throws Exception {
		// TODO Auto-generated method stub
		this.userDao.addLoginTimes(u);
	}
	
		
	//每次登录，返回前台用户等级信息
	@Override
	public int checkPriority(User u) throws Exception {
		// TODO Auto-generated method stub
		return this.userDao.checkPriority(u);
	}
	
	//分页查找用户信息
	@Override
	public List<User> getUsersByPage(int page,int rows) throws Exception {
		// TODO Auto-generated method stub
		final String hql = "from User u";
		page = (page - 1) * rows;
		System.out.println("起始条目为："+page);
		return userDao.findByPage(hql,page,rows);
	}
	
	//获取User表的总数
	@Override
	public Long getTotal(Object o) throws Exception {
		// TODO Auto-generated method stub	
		//转换class，截取并获得 对象的名字
		String className = o.getClass().toString();
 		String b[]=className.split("\\.");
		String obj = b[3];
		String hql = "select count(*) from " + obj;
		return userDao.count(hql);
	}
	
	//更新user表，某用户的全部信息更新
	@Override
	public void editUser(User u) throws Exception {
				
		this.userDao.update(u);
	}
	
	//删除某用户
	@Override
	public void removeUser(User u) throws Exception {
				
		this.userDao.delete(u);
	}
	
	//查找某个用户 利用id
	@Override
	public List<User> findById(int id) throws Exception {
				
		return this.userDao.find(id);
	}
	
}
